import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:table_calendar/table_calendar.dart';

import '../models/calendar_event.dart';
import '../models/dateline_event.dart';
import '../providers/calendar_providers.dart';
import '../providers/dateline_providers.dart';
import '../widgets/dateline_type_filter.dart';
import '../widgets/add_event_dialog.dart';
import '../widgets/add_dateline_event_dialog.dart';

/// 日历主屏幕
class CalendarScreen extends ConsumerStatefulWidget {
  /// 路由名称
  static const routeName = '/calendar';

  const CalendarScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<CalendarScreen> createState() => _CalendarScreenState();
}

class _CalendarScreenState extends ConsumerState<CalendarScreen> {
  late CalendarFormat _calendarFormat;
  late DateTime _focusedDay;
  late DateTime _selectedDay;

  @override
  void initState() {
    super.initState();
    _calendarFormat = CalendarFormat.month;
    _focusedDay = DateTime.now();
    _selectedDay = DateTime.now();
    
    // 从后端加载真实数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 加载日历事件
      ref.read(calendarEventsProvider.notifier).loadEvents();
      // 加载时间线事件
      ref.read(datelineEventsProvider.notifier).loadAllEvents();
      // 加载日历事件类型列表（触发 /api/dateline/type/list 接口调用）
      // 使用 refresh 强制重新加载
      ref.refresh(datelineTypesProvider);
    });
  }

  @override
  Widget build(BuildContext context) {
    // 获取当前选中的日期
    final selectedDate = ref.watch(selectedDateProvider);
    // 获取当前选中的时间线事件类型过滤器
    final datelineTypeFilter = ref.watch(datelineTypeFilterProvider);
    // 获取当前的日历视图类型
    final calendarViewType = ref.watch(calendarViewTypeProvider);
    
    // 根据过滤器获取时间线事件（调用接口）
    final datelineEventsAsync = datelineTypeFilter == null
        ? ref.watch(datelineEventsByTypeProvider(null))
        : ref.watch(datelineEventsByTypeProvider(datelineTypeFilter));

    return Scaffold(
      appBar: AppBar(
        title: const Text('家庭日历'),
        actions: [
          // 日历视图切换按钮
          IconButton(
            icon: const Icon(Icons.calendar_view_month),
            onPressed: () {
              _showViewTypeMenu(context);
            },
          ),
          // 添加事件按钮
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              _showAddEventDialog(context);
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 时间线事件类型过滤器
          const DatelineTypeFilter(),
          
          // 根据日历视图类型显示不同的日历视图
          if (calendarViewType == CalendarViewType.month || 
              calendarViewType == CalendarViewType.week)
            _buildTableCalendar(),
          
          // 事件列表
          Expanded(
            child: calendarViewType == CalendarViewType.all
                ? _buildAllEventsView()
                : _buildFilteredEventList(selectedDate, datelineEventsAsync),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          _showAddDatelineEventDialog(context);
        },
        icon: const Icon(Icons.timeline),
        label: const Text('添加时间线'),
        backgroundColor: Theme.of(context).primaryColor,
      ),
    );
  }

  /// 构建表格形式的日历
  Widget _buildTableCalendar() {
    final calendarViewType = ref.watch(calendarViewTypeProvider);
    final events = ref.watch(calendarEventsProvider);
    // 获取时间线事件类型过滤器
    final datelineTypeFilter = ref.watch(datelineTypeFilterProvider);
    // 根据过滤器获取时间线事件（调用接口）
    final datelineEventsAsync = datelineTypeFilter == null
        ? ref.watch(datelineEventsByTypeProvider(null))
        : ref.watch(datelineEventsByTypeProvider(datelineTypeFilter));
    
    // 创建事件映射，用于在日历上标记有事件的日期
    final eventMap = <DateTime, List<CalendarEvent>>{};
    // 创建时间线事件映射
    final datelineEventMap = <DateTime, List<DatelineEvent>>{};
    
    // 添加日历事件
    for (final event in events) {
      
      final eventDate = DateTime(
        event.startTime.year,
        event.startTime.month,
        event.startTime.day,
      );
      
      if (eventMap[eventDate] == null) {
        eventMap[eventDate] = [];
      }
      
      eventMap[eventDate]!.add(event);
      
      // 如果是重复事件，添加未来的重复日期
      if (event.isRecurring) {
        final now = DateTime.now();
        final endDate = DateTime(now.year + 1, 12, 31); // 展示未来一年的事件
        
        DateTime currentDate = eventDate;
        
        while (currentDate.isBefore(endDate)) {
          DateTime? nextDate;
          
          if (event.recurrenceType == 'daily') {
            nextDate = currentDate.add(const Duration(days: 1));
          } else if (event.recurrenceType == 'weekly') {
            nextDate = currentDate.add(const Duration(days: 7));
          } else if (event.recurrenceType == 'monthly') {
            // 每月同一天
            int nextMonth = currentDate.month + 1;
            int nextYear = currentDate.year;
            if (nextMonth > 12) {
              nextMonth = 1;
              nextYear++;
            }
            // 处理月底天数问题
            int day = currentDate.day;
            while (true) {
              try {
                nextDate = DateTime(nextYear, nextMonth, day);
                break;
              } catch (e) {
                day--; // 如果天数超过了下个月的最大天数，则减少一天
              }
            }
          } else if (event.recurrenceType == 'yearly') {
            // 每年同一天
            nextDate = DateTime(currentDate.year + 1, currentDate.month, currentDate.day);
          }
          
          if (nextDate != null) {
            currentDate = nextDate;
            
            if (eventMap[currentDate] == null) {
              eventMap[currentDate] = [];
            }
            eventMap[currentDate]!.add(event);
          } else {
            break;
          }
        }
      }
    }
    
    // 添加时间线事件到映射中（从异步数据中获取）
    // 处理异步数据：当数据加载完成时添加到映射
    if (datelineEventsAsync.hasValue) {
      final datelineEvents = datelineEventsAsync.value ?? [];
      print('时间线事件数量: ${datelineEvents.length}');
      
      for (final datelineEvent in datelineEvents) {
        final eventDate = DateTime(
          datelineEvent.eventTime.year,
          datelineEvent.eventTime.month,
          datelineEvent.eventTime.day,
        );
        
        if (datelineEventMap[eventDate] == null) {
          datelineEventMap[eventDate] = [];
        }
        
        datelineEventMap[eventDate]!.add(datelineEvent);
      }
    }

    return TableCalendar<CalendarEvent>(
      firstDay: DateTime.utc(2020, 1, 1),
      lastDay: DateTime.utc(2030, 12, 31),
      focusedDay: _focusedDay,
      calendarFormat: calendarViewType == CalendarViewType.month
          ? CalendarFormat.month
          : CalendarFormat.week,
      selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
      eventLoader: (day) {
        final normalizedDay = DateTime(day.year, day.month, day.day);
        return eventMap[normalizedDay] ?? [];
      },
      onDaySelected: (selectedDay, focusedDay) {
        setState(() {
          _selectedDay = selectedDay;
          _focusedDay = focusedDay;
        });
        ref.read(selectedDateProvider.notifier).state = selectedDay;
      },
      onFormatChanged: (format) {
        setState(() {
          _calendarFormat = format;
        });
      },
      onPageChanged: (focusedDay) {
        setState(() {
          _focusedDay = focusedDay;
        });
      },
      calendarStyle: CalendarStyle(
        // 标记事件的样式
        markersMaxCount: 3,
        markerDecoration: BoxDecoration(
          color: datelineTypeFilter?.color ?? Colors.blue,
          shape: BoxShape.circle,
        ),
        // 选中日期的样式
        selectedDecoration: const BoxDecoration(
          color: Colors.blue,
          shape: BoxShape.circle,
        ),
        todayDecoration: BoxDecoration(
          color: Colors.blue.withOpacity(0.3),
          shape: BoxShape.circle,
        ),
      ),
      headerStyle: const HeaderStyle(
        formatButtonVisible: false,
        titleCentered: true,
      ),
      calendarBuilders: CalendarBuilders(
        // 自定义日期单元格，显示事件标题
        markerBuilder: (context, date, events) {
          // 获取该日期的时间线事件
          final normalizedDate = DateTime(date.year, date.month, date.day);
          final datelineEventsForDate = datelineEventMap[normalizedDate] ?? [];
          
          // 合并所有事件
          final allEventsForDate = <dynamic>[...events, ...datelineEventsForDate];
          
          if (allEventsForDate.isEmpty) return const SizedBox.shrink();
          
          return Positioned(
            bottom: 1,
            child: Container(
              width: 35,  // 调整宽度以适应单元格
              child: Column(
                children: [
                  // 最多显示2个事件
                  for (int i = 0; i < allEventsForDate.length && i < 2; i++)
                    Container(
                      margin: const EdgeInsets.only(top: 1),
                      padding: const EdgeInsets.symmetric(horizontal: 2),
                      decoration: BoxDecoration(
                        color: _getEventColor(allEventsForDate[i]).withOpacity(0.7),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        _getEventTitle(allEventsForDate[i]),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 7,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  // 如果有更多事件，显示
                  if (allEventsForDate.length > 2)
                    Container(
                      margin: const EdgeInsets.only(top: 1),
                      padding: const EdgeInsets.symmetric(horizontal: 2),
                      decoration: BoxDecoration(
                        color: Colors.grey.withOpacity(0.7),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        '+${allEventsForDate.length - 2}',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 7,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          );
        },
      ),
      locale: 'zh_CN', // 使用中文显示
    );
  }

  /// 显示日历视图类型选择菜单
  void _showViewTypeMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.calendar_view_month),
                title: const Text('月视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.month;
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.calendar_view_week),
                title: const Text('周视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.week;
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.view_agenda),
                title: const Text('议程视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.agenda;
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.list_alt),
                title: const Text('全部视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.all;
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示添加事件对话框
  void _showAddEventDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const AddEventDialog(),
    );
  }

  /// 显示添加时间线事件对话框
  void _showAddDatelineEventDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const AddDatelineEventDialog(),
    ).then((result) {
      if (result != null && result is DatelineEvent) {
        // 刷新时间线事件列表
        ref.read(datelineEventsProvider.notifier).refresh();
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('时间线事件添加成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    });
  }

  /// 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  /// 获取重复类型文本
  String _getRecurrenceTypeText(String? recurrenceType) {
    switch (recurrenceType) {
      case 'daily':
        return '每天';
      case 'weekly':
        return '每周';
      case 'monthly':
        return '每月';
      case 'yearly':
        return '每年';
      default:
        return '未知';
    }
  }

  /// 格式化提醒时间
  String _formatReminderTime(int minutes) {
    if (minutes >= 1440) { // 1天 = 1440分钟
      return '提前${minutes ~/ 1440}天';
    } else if (minutes >= 60) {
      return '提前${minutes ~/ 60}小时';
    } else {
      return '提前$minutes分钟';
    }
  }

  /// 获取事件类型过滤器名称
  String _getEventTypeFilterName(DatelineEventType? eventType) {
    if (eventType == null) {
      return '';
    }
    
    return eventType.displayName;
  }

  /// 构建过滤后的事件列表（用于日历视图下方）
  Widget _buildFilteredEventList(DateTime selectedDate, AsyncValue<List<DatelineEvent>> datelineEventsAsync) {
    final datelineTypeFilter = ref.watch(datelineTypeFilterProvider);
    
    return datelineEventsAsync.when(
      data: (datelineEvents) {
        // 过滤出选中日期的事件
        final selectedDayEvents = datelineEvents.where((event) {
          final eventDate = event.eventTime;
          return eventDate.year == selectedDate.year &&
                 eventDate.month == selectedDate.month &&
                 eventDate.day == selectedDate.day;
        }).toList();
        
        if (selectedDayEvents.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.event_busy,
                  size: 64,
                  color: Colors.grey,
                ),
                const SizedBox(height: 16),
                Text(
                  '当前没有${_getEventTypeFilterName(datelineTypeFilter)}事件',
                  style: const TextStyle(color: Colors.grey),
                ),
              ],
            ),
          );
        }
        
        // 显示选中日期的事件列表
        return ListView.builder(
          padding: const EdgeInsets.all(8),
          itemCount: selectedDayEvents.length,
          itemBuilder: (context, index) {
            return _buildDatelineEventItem(context, selectedDayEvents[index]);
          },
        );
      },
      loading: () {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
      error: (error, stack) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.red,
              ),
              const SizedBox(height: 16),
              Text(
                '加载事件失败: $error',
                style: const TextStyle(color: Colors.red),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建全部事件视图
  Widget _buildAllEventsView() {
    final datelineTypeFilter = ref.watch(datelineTypeFilterProvider);
    // 根据过滤器获取时间线事件（调用接口）
    final datelineEventsAsync = datelineTypeFilter == null
        ? ref.watch(datelineEventsByTypeProvider(null))
        : ref.watch(datelineEventsByTypeProvider(datelineTypeFilter));
    
    return datelineEventsAsync.when(
      data: (datelineEvents) {
        if (datelineEvents.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.event_busy,
                  size: 64,
                  color: Colors.grey,
                ),
                const SizedBox(height: 16),
                Text(
                  '没有${_getEventTypeFilterName(datelineTypeFilter)}事件',
                  style: const TextStyle(color: Colors.grey),
                ),
              ],
            ),
          );
        }
        
        // 按照日期分组事件
        final groupedEvents = <String, List<DatelineEvent>>{};
        
        for (final event in datelineEvents) {
          final dateKey = _formatDateForGrouping(event.eventTime);
          if (groupedEvents[dateKey] == null) {
            groupedEvents[dateKey] = [];
          }
          groupedEvents[dateKey]!.add(event);
        }
        
        // 按照日期排序
        final sortedKeys = groupedEvents.keys.toList()
          ..sort((a, b) => a.compareTo(b));
        
        return ListView.builder(
          padding: const EdgeInsets.all(8),
          itemCount: sortedKeys.length,
          itemBuilder: (context, index) {
            final dateKey = sortedKeys[index];
            final dateEvents = groupedEvents[dateKey]!;
            
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 日期标题
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  child: Text(
                    dateKey,
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                // 事件列表
                ...dateEvents.map((event) => _buildDatelineEventItem(context, event)),
                const Divider(),
              ],
            );
          },
        );
      },
      loading: () {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
      error: (error, stack) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.red,
              ),
              const SizedBox(height: 16),
              Text(
                '加载事件失败: $error',
                style: const TextStyle(color: Colors.red),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建时间线事件项
  Widget _buildDatelineEventItem(BuildContext context, DatelineEvent event) {
    return Card(
      elevation: 1,
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 事件类型图标
            CircleAvatar(
              radius: 16,
              backgroundColor: event.eventType.color,
              child: IconTheme(
                data: const IconThemeData(color: Colors.white, size: 16),
                child: event.eventType.icon,
              ),
            ),
            const SizedBox(width: 12),
            // 事件标题和时间
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    event.title,
                    style: Theme.of(context).textTheme.titleSmall,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _formatTimeOnly(event.eventTime),
                    style: Theme.of(context).textTheme.bodySmall,
                  ),
                  if (event.description != null && event.description!.isNotEmpty) ...[
                    const SizedBox(height: 4),
                    Text(
                      event.description!,
                      style: Theme.of(context).textTheme.bodySmall,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  if (event.location != null && event.location!.isNotEmpty) ...[
                    const SizedBox(height: 2),
                    Row(
                      children: [
                        const Icon(Icons.location_on, size: 12, color: Colors.grey),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Text(
                            event.location!,
                            style: Theme.of(context).textTheme.bodySmall,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化日期用于分组
  String _formatDateForGrouping(DateTime date) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final tomorrow = today.add(const Duration(days: 1));
    final yesterday = today.subtract(const Duration(days: 1));
    final dateOnly = DateTime(date.year, date.month, date.day);
    
    if (dateOnly == today) {
      return '今天';
    } else if (dateOnly == tomorrow) {
      return '明天';
    } else if (dateOnly == yesterday) {
      return '昨天';
    } else {
      return '${date.year}年${date.month}月${date.day}日';
    }
  }

  /// 格式化时间（仅显示小时和分钟）
  String _formatTimeOnly(DateTime dateTime) {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  /// 获取事件的颜色
  Color _getEventColor(dynamic event) {
    if (event is CalendarEvent) {
      return event.eventType.color;
    } else if (event is DatelineEvent) {
      return event.eventType.color;
    }
    return Colors.grey;
  }

  /// 获取事件的标题
  String _getEventTitle(dynamic event) {
    if (event is CalendarEvent) {
      return event.title;
    } else if (event is DatelineEvent) {
      return event.title;
    }
    return '';
  }
}
